<template>
    <div>
        <el-row>
            <el-col :span="22" id="selectdiv">

                <el-form :inline="true" :model="selectData" class="demo-form-inline">
                    <el-form-item label="图片位置" label-position="left">
                        <el-input  v-model="selectData.imageposition" placeholder="图片应用位置"></el-input>
                    </el-form-item>
                    <el-form-item label="图片名字" label-position="left">
                        <el-input  v-model="selectData.imagename" placeholder="图片名字"></el-input>
                    </el-form-item>
                    <el-form-item label="图片格式" label-position="left">
                        <el-input v-model="selectData.imageformat" placeholder="图片格式"></el-input>
                    </el-form-item>
                    <el-form-item label="图片链接" label-position="left">
                        <el-input v-model="selectData.imageurl" placeholder="图片链接"></el-input>
                    </el-form-item>
                    <el-form-item style="width: 80px;">
                        <el-button size="small" type="primary" @click="findByData" >查询</el-button>
                    </el-form-item>
                    <el-form-item style="width: 80px;" >
                        <el-button size="small" type="primary" @click="clear">清除</el-button>
                    </el-form-item>
                </el-form>
                
            </el-col>
            <el-col :span="2" style="margin-bottom: 22px;">
                <div class="grid-content bg-purple-light">
                    <el-button size="small" type="primary" @click="dialogFormVisible = true" style="margin-top:6px;z-index:1;position:relative">新增</el-button>
                    <!-- <el-button type="primary" @click="showAddModal">新增</el-button> -->
                    <el-dialog title="新增信息" :visible.sync="dialogFormVisible" id="adddialog" :close-on-click-modal="false"  @close="resetForm('addformdata')">
                        <el-form :model="addformData" class="parentBox" ref="addformData">
                            <el-form-item label="图片上传" :label-width="formLabelWidth" prop="imgUrl">
                                <el-upload class="upload-demo" 
                                ref="upload" 
                                action=""  
                                :on-change="handleChange"
                                :headers="headers"    
                                :before-upload="beforeUpload" 
                                :on-success="handleSuccess" 
                                :auto-upload="false">
                                    <el-button slot="trigger">选取图片</el-button>
                                    <el-button v-if="!addformData.imgUrl" @click="submitUpload">开始上传</el-button>
                                </el-upload>
                                <el-card   shadow="hover">
                                    <div title="点击删除图片" v-if="addformData.imgUrl" class="gbtpBox" @click="imageRemove"><span>×</span></div>
                                    <img v-if="addformData.imgUrl" :src="addformData.imgUrl" alt="已上传图片" style="width:200px; height:200px" />
                                </el-card>
                                
                                
                            </el-form-item>
                            <el-form-item label="图片名称" :label-width="formLabelWidth" prop="imgName">
                                <el-input v-model="addformData.imgName" ></el-input>
                            </el-form-item>
                            <el-form-item label="图片链接" :label-width="formLabelWidth" prop="imgUrl">
                                <el-input v-model="addformData.imgUrl" autocomplete="off" :value="addformData.imgUrl" :readonly="true"></el-input>
                            </el-form-item>
                            <el-form-item label="图片位置" :label-width="formLabelWidth" prop="imgPosition">
                                <el-input v-model="addformData.imgPosition" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="图片格式" :label-width="formLabelWidth" prop="imgFormat">
                                <el-input v-model="addformData.imgFormat" autocomplete="off" :value="addformData.imgFormat"></el-input>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="cancel">取 消</el-button>
                            <el-button type="primary" @click="insertNewImg">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
            </el-col>
        </el-row>
        <!-- 新增按钮 -->
        

        <!-- 表格展示 -->
        <el-table :data="tableData" :height="tableHeight" style="width: 100%" border>
            <el-table-column prop="imgId" label="ID" ></el-table-column>
            <el-table-column label="图片">
                <template slot-scope="scope">
                    <el-image style="width: 100px; height: 100px" :src="scope.row.imgUrl" 
                        :preview-src-list="[scope.row.imgUrl]"  title="scope.row.imgurl">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="imgUrl" label="Url">
                <template slot-scope="scope">
                    <a :href="scope.row.imgUrl" target="_blank" class="buttonText">{{scope.row.imgUrl}}</a>
                </template>
            </el-table-column>
            <el-table-column prop="imgName" label="图片名字"></el-table-column>
            <el-table-column prop="imgPosition" label="图片位置"></el-table-column>
            <el-table-column prop="imgCreatetime" label="创建时间"></el-table-column>
            <el-table-column prop="imgUpdatetime" label="更新时间"></el-table-column>
            <!-- 其他列... -->

            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button size="small" @click="editRow(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteRow(scope.$index, scope.row.imgId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
        </el-pagination>

        <!-- 编辑弹窗 -->
        <el-dialog :visible.sync="UpdateVisible" title="编辑信息">
            <p>如需修改图片，请先选择图片，然后上传</p>
            <el-form ref="editformData" :model="editformData">
                <el-form-item label="图片上传" :label-width="formLabelWidth" prop="imgUrl">
                    <el-upload class="upload-demo" ref="edit_upload" action="" :on-change="handleChange" :headers="headers"
                        :before-upload="beforeUpload" :on-success="edit_handleSuccess" :auto-upload="false">
                        <el-button slot="trigger">选取图片</el-button>
                        <el-button @click="edit_submitUpload">开始上传</el-button>
                    </el-upload>
                    <el-card shadow="hover">
                        <div title="点击删除图片" v-if="editformData.imgUrl" class="gbtpBox" @click="editimageRemove"><span>×</span></div>
                        <img v-if="editformData.imgUrl" :src="editformData.imgUrl" alt="已上传图片" style="width:200px; height:200px" />
                    </el-card>
            
            
                </el-form-item>
                <el-form-item label="图片名称" :label-width="formLabelWidth" prop="imgName">
                    <el-input v-model="editformData.imgName"></el-input>
                </el-form-item>
                <el-form-item label="图片链接" :label-width="formLabelWidth" prop="imgUrl">
                    <el-input v-model="editformData.imgUrl" autocomplete="off" :value="editformData.imgUrl"
                        :readonly="true"></el-input>
                </el-form-item>
                <el-form-item label="图片位置" :label-width="formLabelWidth" prop="imgPosition">
                    <el-input v-model="editformData.imgPosition" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图片格式" :label-width="formLabelWidth" prop="imgFormat">
                    <el-input v-model="editformData.imgFormat" autocomplete="off" :value="editformData.imgFormat"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="editImg">确定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        data() {
            return {
                tableHeight:window.innerHeight- 200,
                headers: { 'Content-Type': 'multipart/form-data' },
                dialogUploadVisible:false,
                disabled:false,
                dialogFormVisible: false,
                formLabelWidth: '120px',
                acceptAstrict: '.jpg,.jpeg,.png,.JPG,.PNG',
                file: null,
                selectData:{
                    imageposition:'',
                    iamgename:'',
                    imageurl:'',
                    imageformat:''
                },
                tableData: []
                , // 表格数据
                currentPage: 1, // 当前页码
                pageSize: 10, // 每页显示数量
                totalCount: 0, // 总记录数
                addformData:{
                    imgId: '',
                    imgUrl: '',
                    imgName: '',
                    imgFormat: '',
                    imgPosition: '',
                    imgCreatetime: '',
                    imgUpdatetime: ''
                },
                editformData: {
                    imgId: '',
                    imgUrl: '',
                    imgName: '',
                    imgFormat: '',
                    imgPosition: '',
                    imgCreatetime: '',
                    imgUpdatetime: ''
                }, // 编辑表单数据
                UpdateVisible: false, // 是否显示编辑弹窗
            };
        },
        methods: {
            getHeight() {
                console.log("tableHeight:"+this.tableHeight);
                this.tableHeight = window.innerHeight-200 ;
            },
            async fetchData() {
                // 获取后台数据，假设使用axios
                console.log("fetchdata"+this.currentPage+ this.pageSize+","+ this.selectData.imageurl+" "+ this.selectData.imageposition+" "+ this.selectData.imagename);
                this.$axios({
                    method:'post',
                    url: 'http://localhost:8080/image',
                    data: {
                        page: this.currentPage, 
                        pageSize: this.pageSize, 
                        imgUrl: this.selectData.imageurl,
                        imgPosition: this.selectData.imageposition,
                        imgFormat: this.selectData.imageformat,
                        imgName: this.selectData.imagename
                    },
                    headers:{
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res=>{ 
                    //this.tableData = res.data.data;
                    //this.totalCount = res.data.total;
                    /*tableData: [{
                        imgId: '',
                        imgUrl: '',
                        imgName: '',
                        imgFormat: '',
                        imgPosition: '',
                        imgCreatetime: '',
                        imgUpdatetime: '',
                    }]*/
                    this.totalCount = res.data.data.total;
                    this.tableData = res.data.data.rows;
                    console.log(this.tableData);
                    /*this.tableData.imgUrl = res.data.data.rows.imgUrl;
                    this.tableData.imgName = res.data.data.rows.imgName;
                    this.tableData.imgFormat = res.data.data.rows.imgFormat;
                    this.tableData.imgFormat = res.data.data.rows.imgFormat;
                    this.tableData.imgCreatetime = res.data.data.rows.imgCreatetime;
                    this.tableData.imgUpdatetime = res.data.data.rows.imgUpdatetime;*/
                })
                
            },
             handleChange(file) {
                console.log(file);
                this.file = file.raw;
                console.log(this.file);
            },
            // 上传前的钩子，可以在此处自定义上传逻辑
            beforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt10M = file.size / (1024*1024) < 10;
                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
                }
                if (!isLt10M) {
                    this.$message.error('上传图片大小不能超过 10MB!');
                }
                return isJPG && isLt500K;
            },
            // 成功上传后的钩子
            async edit_handleSuccess(response,file){
                console.log("response"+response);
                const fileName = this.file.name;
                this.editformData.imgName = fileName.slice(0, fileName.lastIndexOf('.'));
                this.editformData.imgFormat = fileName.slice(fileName.lastIndexOf('.') + 1);
                this.editformData.imgUrl = response.data.data;
            },
            async handleSuccess(response, file) {
                // 假设后端返回的是上传到OSS后的图片URL
                const fileName = this.file.name;
                this.addformData.imgName = fileName.slice(0, fileName.lastIndexOf('.'));
                this.addformData.imgFormat = fileName.slice(fileName.lastIndexOf('.') + 1);
                this.addformData.imgUrl = response.data.data;
            },
            async edit_submitUpload(){
                if (this.file) {
                    const formData = new FormData();
                    formData.append('file', this.file);
                    try {
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/image/upload',
                            data: formData,

                        }).then(res => {
                            //this.tableData = res.data.data;
                            //this.totalCount = res.data.total;

                            this.edit_handleSuccess(res)
                        })

                    } catch (error) {
                        console.error('上传失败:', error);
                        this.$message.error('上传图片到OSS失败!');
                    }
                } else {
                    this.$message.warning('请先选择图片！');
                }
            },
            async submitUpload() {
                console.log(this.file);
                if (this.file) {
                    const formData = new FormData();
                    formData.append('file', this.file);
                    try{
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/image/upload',
                            data: formData,
                            
                        }).then(res => {
                            //this.tableData = res.data.data;
                            //this.totalCount = res.data.total;
                            
                            this.handleSuccess(res)
                        })
                        
                    }catch(error){
                        console.error('上传失败:', error);
                        this.$message.error('上传图片到OSS失败!');
                    }
                }else{
                    this.$message.warning('请先选择图片！');
                }
            },
            editimageRemove(){
                this.editformData.imgUrl = '';
                
                this.editformData.imgFormat = '';
                this.$message({
                    message: '删除图片成功',
                    type: 'success'
                })
            },
            // 删除图片
            imageRemove() {
                this.addformData.imgUrl = '';
                this.addformData.imgName = '';
                this.addformData.imgFormat ='';
                this.$message({
                    message: '删除图片成功',
                    type: 'success'
                })
            },
            findByData(){
                this.fetchData();
            },
            clear(){
                this.selectData.imageurl='';
                this.selectData.imageposition ='';
                this.selectData.imageformat ='';
                this.selectData.imagename ='';
                this.fetchData();
            },
            
            insertNewImg(){
                this.$axios({
                    method: 'post',
                    url: 'http://localhost:8080/image/add',
                    data: this.addformData
                }).then(res=>{
                    if(res.data.code==1){
                        alert("success!");
                        this.fetchData();
                        //this.imageRemove();
                        /*this.addformData.imgPosition='';
                        this.addformData.imgUrl = '';
                        this.addformData.imgName = '';
                        this.addformData.imgFormat = '';
                        this.file=null;*/
                        this.$refs.addformData.resetFields();
                        this.$refs.upload.clearFiles();
                        
                    }else{
                        alert(res.data.msg);
                    }
                })
                this.dialogFormVisible = false;
                

            },
            resetForm(addformData) {
                this.$refs.addformData.resetFields()
            },

            cancel(){
                this.dialogFormVisible = false
            },
           
            showAddModal() {
                this.formData = {};
                this.UpdateVisible = true;
            },
            editRow(index, row) {
                this.editformData = Object.assign({}, row);
                console.log(this.editformData);
                this.UpdateVisible = true;
            },
            deleteRow(index, imgId) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(action => {
                    if(action==='confirm'){
                        console.log(imgId);
                        this.$axios.delete(`http://localhost:8080/image/delete/${imgId}`).then(res => {
                            if (res.data.code == 1) {
                                this.fetchData();
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '删除失败!出现错误'
                                });
                            }
                            // 更新服务器返回的总记录数（这里仅为了演示，实际可能需要再次获取）

                        });
                    } 
                }).catch(action => {
                    if(action==='cancel'){
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    }
                    
                });
                
                
            },
            closeDialog() {
                this.UpdateVisible = false;
                this.$refs.editformData.resetFields();
            },
            editImg() { 
                this.$axios({
                    method: 'post',
                    url: 'http://localhost:8080/image/edit',
                    data: this.editformData
                }).then(res => {
                    if (res.data.code == 1) {
                        alert("success!");
                        this.fetchData();
                        //this.imageRemove();
                        /*this.addformData.imgPosition='';
                        this.addformData.imgUrl = '';
                        this.addformData.imgName = '';
                        this.addformData.imgFormat = '';
                        this.file=null;*/
                        this.$refs.editformData.resetFields();
                        this.$refs.edit_upload.clearFiles();

                    } else {
                        alert(res.data.msg);
                    }
                })
                this.UpdateVisible = false;
                

            },
            
            handleSizeChange(size) {
                this.pageSize = size;
                this.fetchData();
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.fetchData();
            },
        },
        created(){
            window.addEventListener('resize', this.getHeight)
        },
        mounted() {
            this.fetchData();
        },
    };
</script>
<style lang="less">
#selectdiv{
    .el-form-item{
        width: 20%;
        margin-right: 0;
        .el-form-item__content {
            line-height: 40px;
            position: relative;
            font-size: 14px;
            width: 140px;
        }
    }
    
}
#adddialog{
    .el-form-item{
        width: 70%;
        margin-right: 0;
        .el-form-item__content{
            line-height: 40px;
            width: 70%;
            font-size: 14px;
        }
    }
    
}

 .parentBox {
    padding: 20px;
}
.iconBox i {
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    font-size: 20px;
    color: #8c939d;
    font-weight: bold;
    border: 1px #8c939d dashed;
    border-radius: 4px;
    background: rgb(251, 253, 255);
}
.iconBox i:hover {
    border: 1px rgb(64, 158, 255) dashed;
}
.el-image {
    width: 100px;
    height: 100px;
    border-radius: 4px;
    border: 1px solid rgb(192, 204, 218);
}

.gbtpBox {
    position: relative;
}
.gbtpBox span {
    
    top: -110px;
    left: 90px;
    cursor: pointer;
    font-size: 16px;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    text-align: center;
    line-height: 16px;
    background: rgb(245, 108, 108);
    color: #fff;
}
.gbtpBox span:hover {
    background: rgb(247, 137, 137);
    color: #fff;
}
::v-deep .avatar-uploader {
    height: 0px;
}

</style>